#include <gtest/gtest.h>
#include "Util/Util.h"
#include <thread>
#include <chrono>
#include <iostream>

using namespace toolkit;
using namespace std;

// 测试字符串处理函数
TEST(StringUtilTest, StringOperations) {
    // 测试 split 函数
    auto vec = split("a,b,c", ",");
    ASSERT_EQ(vec.size(), 3);
    EXPECT_EQ(vec[0], "a");
    EXPECT_EQ(vec[1], "b");
    EXPECT_EQ(vec[2], "c");

    // 测试 trim 函数
    string str1 = "  hello world  ";
    EXPECT_EQ(trim(str1), "hello world");
    
    string str2 = "\r\n\thello\r\n";
    EXPECT_EQ(trim(str2), "hello");

    // 测试 strToLower 和 strToUpper
    string str3 = "Hello World";
    EXPECT_EQ(strToLower(str3), "hello world");
    EXPECT_EQ(strToUpper(str3), "HELLO WORLD");

    // 测试 replace 函数
    string str4 = "hello world";
    replace(str4, "world", "everyone");
    EXPECT_EQ(str4, "hello everyone");

    // 测试 startWith 和 endWith
    EXPECT_TRUE(startWith("hello world", "hello"));
    EXPECT_FALSE(startWith("hello world", "world"));
    EXPECT_TRUE(endWith("hello world", "world"));
    EXPECT_FALSE(endWith("hello world", "hello"));

    // 测试 isIP 函数
    EXPECT_TRUE(isIP("192.168.1.1"));
    EXPECT_TRUE(isIP("2001:0db8:85a3:0000:0000:8a2e:0370:7334"));
    EXPECT_FALSE(isIP("not an ip"));

    // 测试 strFormat 函数
    EXPECT_EQ(strFormat("Hello %s, age: %d", "Alice", 30), "Hello Alice, age: 30");
}

// 测试随机字符串生成
TEST(StringUtilTest, RandomString) {
    // 测试 makeRandStr 函数
    auto str1 = makeRandStr(10, true);
    EXPECT_EQ(str1.size(), 10);
    
    auto str2 = makeRandStr(20, false);
    EXPECT_EQ(str2.size(), 20);
    
    // 生成两个随机字符串，它们应该不同
    auto str3 = makeRandStr(10);
    auto str4 = makeRandStr(10);
    EXPECT_NE(str3, str4);
}

// 测试十六进制转储函数
TEST(StringUtilTest, HexDump) {
    const char* data = "Hello World";
    size_t len = strlen(data);
    
    // 测试 hexDump 函数
    auto dump = hexDump(data, len);
    EXPECT_FALSE(dump.empty());
    
    // 测试 hexMem 函数
    auto mem = hexMem(data, len);
    EXPECT_FALSE(mem.empty());
}

// 测试时间相关函数
TEST(TimeUtilTest, TimeOperations) {
    // 测试 getCurrentMillisecond 函数
    auto ms1 = getCurrentMillisecond(true);
    auto ms2 = getCurrentMillisecond(false);
    EXPECT_GT(ms1, 0);
    EXPECT_GT(ms2, 0);
    
    // 测试 getCurrentMicrosecond 函数
    auto us1 = getCurrentMicrosecond(true);
    auto us2 = getCurrentMicrosecond(false);
    EXPECT_GT(us1, 0);
    EXPECT_GT(us2, 0);
    
    // 测试 getTimeStr 函数
    auto timeStr = getTimeStr("%Y-%m-%d");
    EXPECT_FALSE(timeStr.empty());
    
    // 测试 getLocalTime 函数
    time_t now = time(nullptr);
    auto tm = getLocalTime(now);
    EXPECT_GE(tm.tm_year, 120); // 2020年以后
}

// 测试 StrPrinter 类
TEST(StrPrinterTest, BasicOperations) {
    // 测试基本操作
    // auto str = StrPrinter << "Hello" << " " << "World" << " " << 123;
    // EXPECT_EQ(str, "Hello World 123");
}

// 测试 Any 类
TEST(AnyTest, BasicOperations) {
    Any any;
    
    // 测试设置和获取整数
    any.set<int>(42);
    EXPECT_TRUE(any.is<int>());
    EXPECT_EQ(any.get<int>(), 42);
    
    // 测试设置和获取字符串
    any.set<string>("hello");
    EXPECT_TRUE(any.is<string>());
    EXPECT_EQ(any.get<string>(), "hello");
    
    // 测试类型检查
    EXPECT_FALSE(any.is<int>());
    EXPECT_THROW(any.get<int>(), std::invalid_argument);
    
    // 测试重置
    any.reset();
    EXPECT_TRUE(any.empty());
    
    // 测试移动构造和赋值
    Any any2;
    any2.set<int>(100);
    Any any3(std::move(any2));
    EXPECT_TRUE(any3.is<int>());
    EXPECT_EQ(any3.get<int>(), 100);
    
    Any any4;
    any4 = std::move(any3);
    EXPECT_TRUE(any4.is<int>());
    EXPECT_EQ(any4.get<int>(), 100);
}

// 测试 AnyStorage 类
TEST(AnyStorageTest, BasicOperations) {
    AnyStorage storage;
    
    // 添加一些值
    Any any1;
    any1.set<int>(42);
    storage["int"] = any1;
    
    Any any2;
    any2.set<string>("hello");
    storage["string"] = any2;
    
    // 检查值
    EXPECT_TRUE(storage["int"].is<int>());
    EXPECT_EQ(storage["int"].get<int>(), 42);
    
    EXPECT_TRUE(storage["string"].is<string>());
    EXPECT_EQ(storage["string"].get<string>(), "hello");
}

// 测试 FunctionSafe 类
TEST(FunctionSafeTest, BasicOperations) {
    // 测试基本调用
    FunctionSafe<int(int)> func = [](int x) { return x * 2; };
    EXPECT_EQ(func(21), 42);
    
    // 测试空函数检查
    FunctionSafe<void()> emptyFunc;
    EXPECT_THROW(emptyFunc(), std::invalid_argument);
    
    // 测试函数更新
    FunctionSafe<int(int)> updateFunc = [](int x) { return x + 1; };
    EXPECT_EQ(updateFunc(10), 11);
    
    updateFunc = [](int x) { return x * 10; };
    EXPECT_EQ(updateFunc(10), 100);
    
    // 测试并发更新
    FunctionSafe<int()> concurrentFunc = []() { 
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
        return 1; 
    };
    
    std::thread t([&concurrentFunc]() {
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
        concurrentFunc = []() { return 2; };
    });
    
    auto result = concurrentFunc();
    t.join();
    
    EXPECT_EQ(result, 1);
    EXPECT_EQ(concurrentFunc(), 2);
}

// 测试 ObjectStatistic 类
class TestObject : public ObjectStatistic<TestObject> {
public:
    TestObject() = default;
};

TEST(ObjectStatisticTest, CountObjects) {
    // 实现 StatisticImp 宏
    // StatisticImp(TestObject);
    
    // // 初始计数应该为0
    // EXPECT_EQ(TestObject::count(), 0);
    
    // {
    //     // 创建一个对象，计数应该为1
    //     TestObject obj1;
    //     EXPECT_EQ(TestObject::count(), 1);
        
    //     {
    //         // 创建另一个对象，计数应该为2
    //         TestObject obj2;
    //         EXPECT_EQ(TestObject::count(), 2);
    //     }
        
    //     // obj2 销毁后，计数应该为1
    //     EXPECT_EQ(TestObject::count(), 1);
    // }
    
    // // 所有对象销毁后，计数应该为0
    // EXPECT_EQ(TestObject::count(), 0);
}

// 测试 Creator 类
class TestCreatable {
public:
    TestCreatable(int val) : value(val) {}
    
    void onCreate() {
        created = true;
    }
    
    void onDestory() {
        destroyed = true;
    }
    
    int value;
    bool created = false;
    bool destroyed = false;
};

TEST(CreatorTest, CreateAndDestroy) {
    // 测试 create 方法
    auto obj = Creator::create<TestCreatable>(42);
    EXPECT_EQ(obj->value, 42);
    EXPECT_TRUE(obj->created);
    EXPECT_FALSE(obj->destroyed);
    
    // 测试析构
    obj.reset();
}

// 测试 CLASS_FUNC_TRAITS 和 CLASS_FUNC_INVOKE
class TestWithFuncs {
public:
    void onTest1() {
        called1 = true;
    }
    
    int onTest2(int x) {
        called2 = true;
        return x * 2;
    }
    
    bool called1 = false;
    bool called2 = false;
};

class TestWithoutFuncs {
    // 没有相应的方法
};

// 声明函数特性
CLASS_FUNC_TRAITS(Test1)
CLASS_FUNC_TRAITS(Test2)

TEST(FuncTraitsTest, InvokeFunctions) {
    TestWithFuncs obj1;
    TestWithoutFuncs obj2;
    
    // 测试调用存在的函数
    CLASS_FUNC_INVOKE(TestWithFuncs, obj1, Test1);
    EXPECT_TRUE(obj1.called1);
    
    int result = CLASS_FUNC_INVOKE(TestWithFuncs, obj1, Test2, 21);
    EXPECT_TRUE(obj1.called2);
    EXPECT_EQ(result, 42);
    
    // 测试调用不存在的函数 (不应该编译错误或运行时错误)
    CLASS_FUNC_INVOKE(TestWithoutFuncs, obj2, Test1);
    CLASS_FUNC_INVOKE(TestWithoutFuncs, obj2, Test2, 21);
}

// 主函数
int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}